<template>
	<div class="box_contain">
		<leftPannel
			:is-edit="isEdit"
			@edit-shp="editShp"
			@watch-shp="watchShp"
			@exit-edit="exitEdit"
			@watchshpTwo="watchshpTwo"
			@tiflegendshow="controltifLegendshow"
			:type="'task'"
		/>
		<rightPopupshp />
		<!-- <vectorAnalysis /> -->
		<rightLegend v-if="legendStatus" />
		<rightLegendShp v-if="legendShpStatus" />
		<div id="map" ref="mapRef" class="map-container">
			<!-- <div id="scale-line" class="scale-line"></div> -->
			<router-view />
		</div>
		<div id="map1" ref="mapRef" class="map-container" style="left: 50%">
			<!-- <div id="scale-line" class="scale-line"></div> -->
			<router-view />
		</div>
	</div>
</template>

<script setup lang="ts">
import leftPannel from "./left-pannel.vue";
import rightPopupshp from "./changeDetecitonPop.vue";
import rightLegend from "../ai-processing/right-legend.vue";
import mapTool from "@/utils/maptools/map";
import rightLegendShp from "../ai-processing/right-legendShp.vue";
// @ts-ignore
import { Map } from "ol/Map";
import { useTaskStore } from "@/store";
import MapTool from "@/components/map-tool/index.vue";
import FeatureEdit from "@/components/feature-edit/index.vue";
import type { taskListItem } from "@/api/ai-processing/types";
import { getTaskDetail } from "@/api/ai-processing";
import { fakelogin, getInfo } from "@/api/user/index";
import { getToken, setToken } from "@/utils/auth";
import { useUserStore } from "@/store";

/**------------------------地图相关------------------------------*/
let map: Map;
let map1: Map;

const pointerRef = ref(); // 显示坐标的dom
const mapRef = ref(); // 显示地图的dom
const pointCoordinate = ref([]); // 鼠标指针所在位置坐标
// 图例显隐
const taskStore = useTaskStore();
const legendStatus = ref(false);
const controltifLegendshow = (flag: boolean) => {
	legendStatus.value = flag;
};
const legendShpStatus = computed(() => taskStore.vecLegendShow);
// 鼠标移开事件，显示坐标
const mouseOutEvent = () => {
	pointerRef.value.style.display = "none";
};

// 鼠标移动事件，获取鼠标点坐标
const mouseMoveEvent = (event: any) => {
	pointerRef.value.style.display = "block";
	pointCoordinate.value = event.coordinate.map((item: number) => item.toFixed(6));
};
const token = ref("");
const userStore = useUserStore();

const faketestlogin = async () => {
	if (getToken()) {
		return;
	}
	let data = {
		username: "testw",
		password: "123456",
	};
	console.log(data);
	let res = await fakelogin(data);
	if (res.code !== 200) {
		console.log(res);
		return;
	}
	setToken(res.token);
	token.value = res.token;
	let userRes = await getInfo();
	let userInfo = userRes.user;
	console.log(userInfo);
	userStore.setInfo({
		userName: userInfo.userName,
		nickName: userInfo.nickName,
		userCode: userInfo.userCode,
		userId: userInfo.userId,
		userRole: userRes.permissions[0],
		ftpInfo: userRes.ftp.protocolType + "://" + userRes.ftp.serverIp + ":" + userRes.ftp.serverPort,
		ftpPwd: userInfo.ftpPwd,
	});
	// console.log("fakelogin");
};

const initComponent = async () => {
	await faketestlogin();
	// 其他组件加载逻辑
	console.log("组件加载完成");
};
onBeforeMount(() => {
	initComponent();
	console.log("11111");
});
onMounted(() => {
	// map = mapTool.initMap(["img_", "cia_", "ibo_"], "map", "ai-interpretation", {
	// 	scaleLine: "scale-line",
	// });
	// map?.addEventListener("pointermove", mouseMoveEvent);
	// // openlayers中无鼠标移出事件，这里使用dom元素代替
	// mapRef.value.addEventListener("mouseout", mouseOutEvent);
	map = mapTool.initMap(["img_", "cia_", "ibo_"], "map", "ai-interpretation", {
		scaleLine: "scale-line",
	});
	map1 = mapTool.initMap(["img_", "cia_", "ibo_"], "map1", "ai-interpretation1", {
		scaleLine: "scale-line",
	});
	syncView(map, map1);
	syncView(map1, map);
});
const throttle = (func, limit) => {
	let lastFunc;
	let lastRan;

	return function (...args) {
		if (!lastRan) {
			func.apply(this, args);
			lastRan = Date.now();
		} else {
			clearTimeout(lastFunc);
			lastFunc = setTimeout(() => {
				if (Date.now() - lastRan >= limit) {
					func.apply(this, args);
					lastRan = Date.now();
				}
			}, limit - (Date.now() - lastRan));
		}
	};
};

const syncView = (sourceMap: any, targetMap: any) => {
	const sourceView = sourceMap.getView();
	const targetView = targetMap.getView();

	// const updateTargetView = () => {
	// 	targetView.setCenter(sourceView.getCenter());
	// 	targetView.setResolution(sourceView.getResolution());
	// };
	const updateTargetView = throttle(() => {
		console.log("update");

		targetView.setCenter(sourceView.getCenter());
		targetView.setResolution(sourceView.getResolution());
	}, 10); // 每 100 毫秒调用一次
	// 监听视图变化事件
	sourceView.on("change:center", updateTargetView);
	sourceView.on("change:resolution", updateTargetView);
	sourceMap.on("wheel", (event) => {
		event.preventDefault(); // 阻止默认滚轮事件

		const delta = event.originalEvent.deltaY; // 获取滚轮滚动值
		console.log(delta);

		const currentResolution = sourceView.getResolution();
		const minResolution = sourceView.getMinResolution(); // 获取最小分辨率
		const maxResolution = sourceView.getMaxResolution(); // 获取最大分辨率

		// 调整灵敏度，这里根据 delta 值判断是放大还是缩小
		let newResolution = delta > 0 ? currentResolution * 1.2 : currentResolution * 0.8;

		// 确保新分辨率在最大和最小范围之间
		if (newResolution < minResolution) {
			newResolution = minResolution;
		} else if (newResolution > maxResolution) {
			newResolution = maxResolution;
		}

		sourceView.setResolution(newResolution);
	});
};
onBeforeUnmount(() => {
	map?.removeEventListener("pointermove", mouseMoveEvent);
	mapRef.value.removeEventListener("mouseout", mouseOutEvent);
});
/**------------------------地图相关------------------------------*/

/**------------------------解译任务相关------------------------------*/
// 是否为编辑状态
const isEdit = ref(false);
// 当前编辑任务
const curItem = ref<taskListItem | undefined>(undefined);
// 编辑矢量
const editShp = (item: taskListItem, flag: boolean) => {
	curItem.value = item;
	isEdit.value = flag;
	legendStatus.value = flag;
	flag && watchShp(item, flag);
	!flag && exitEdit();
};
// 查看矢量
const watchShp = async (item: taskListItem, flag: boolean, locationGeo = "") => {
	// todo 从这里需要完成查看矢量的逻辑，加载矢量边界，加载任务中的tif底图
	// console.log(item);
	// 移除所有切片图层、以及清除矢量图层中要素
	mapTool.removeAllSlicingLayer("ai-interpretation");
	mapTool.clearVectorLayer("ai-interpretation");
	legendStatus.value = flag;
	if (!flag) {
		return;
	}
	if (!locationGeo) {
		// 定位到矢量边界
		mapTool.locationByWkt("ai-interpretation", item.area);
		// 加载tif底图
		mapTool.addSlicingLayer("ai-interpretation", item.tifFilePath);
	}
	// 加载矢量边界
	mapTool.loadFeatureByWkt("ai-interpretation", item.area, item.taskId, false, [
		"#1266E4",
		"#00000000",
	]);
	// mapTool
	// 获取矢量信息加载矢量 todo 不同的矢量类型应该渲染不同的样式
	let res = await getTaskDetail(item.taskId);
	// console.log(res);
	for (const iterator of res.rows) {
		mapTool.loadFeatureByWkt(
			"ai-interpretation",
			iterator.geo,
			iterator.id + "_" + iterator.interpretType,
			true,
			[
				BASE_CONFIG["vectorColor"][iterator.interpretType]["strokeColor"],
				BASE_CONFIG["vectorColor"][iterator.interpretType]["fillColor"],
			]
		);
	}
	if (locationGeo) {
		// mapTool.locationByWkt("ai-interpretation", locationGeo);
		// mapTool.mapList["ai-interpretation"]?.getView();
	}
};
const watchshpTwo = async (
	item: taskListItem,
	flag: boolean,
	mindex: string,
	derection: string,
	locationGeo = ""
) => {
	// todo 从这里需要完成查看矢量的逻辑，加载矢量边界，加载任务中的tif底图
	console.log(item, mindex);
	// 移除所有切片图层、以及清除矢量图层中要素
	mapTool.removeAllSlicingLayer(mindex);
	mapTool.clearVectorLayer(mindex);
	legendStatus.value = flag;
	// 定位到矢量边界
	mapTool.locationByWkt(mindex, item.area);
	// 加载tif底图
	mapTool.addSlicingLayer(mindex, derection == "left" ? item.preFilePath : item.lastFilePath);

	// 加载矢量边界
	mapTool.loadFeatureByWkt(mindex, item.area, item.taskId, false, ["#1266E4", "#00000000"]);
	// mapTool
	// 获取矢量信息加载矢量 todo 不同的矢量类型应该渲染不同的样式
	let res = await getTaskDetail(item.taskId);
	// console.log(res);
	for (const iterator of res.rows) {
		mapTool.loadFeatureByWkt(
			mindex,
			iterator.geo,
			iterator.id + "_" + iterator.interpretType,
			true,
			[
				BASE_CONFIG["vectorColor"][iterator.interpretType]["strokeColor"],
				BASE_CONFIG["vectorColor"][iterator.interpretType]["fillColor"],
			]
		);
	}
	if (locationGeo) {
		// mapTool.locationByWkt("ai-interpretation", locationGeo);
		// mapTool.mapList["ai-interpretation"]?.getView();
	}
};
// 退出编辑
const exitEdit = () => {
	isEdit.value = false;
	// 移除所有切片图层、以及清除矢量图层中要素
	mapTool.removeAllSlicingLayer("ai-interpretation");
	mapTool.clearVectorLayer("ai-interpretation");
	legendStatus.value = false;
};
/**------------------------解译任务相关------------------------------*/
</script>
<style scoped lang="scss">
.box_contain {
	position: relative;
	top: 4rem;
	left: 70px;
	// width: 100%;
	width: calc(100% - 70px);
	height: 100%;
	display: flex;
}
.map-container {
	position: absolute;

	width: 50%;
	height: 100%;
	.pointer-coordinate {
		display: none;
		position: fixed;
		right: 25px;
		bottom: 5px;
		font-size: 14px;
		color: rgba(255, 255, 255, 1);
		z-index: 2023;
		span {
			display: inline-block;
			padding: 0 16px;
		}
	}
	.scale-line {
		position: fixed;
		bottom: 40px;
		right: 25px;
		font-size: 14px;
		color: #fff;
		text-align: center;
		z-index: 2023;
		&::before {
			content: "";
			position: absolute;
			left: 0;
			bottom: 0;
			height: 70%;
			width: 100%;
			border: 1px solid #fff;
			border-top: 0;
		}
	}
	.map-tool {
		position: fixed;
		top: 220px;
		right: 20px;
		z-index: 10;
	}
	.feature-edit {
		position: fixed;
		top: 86px;
		left: 50%;
		transform: translateX(calc(-50% - 48px));
		z-index: 10;
	}
	.back {
		display: flex;
		align-items: center;
		position: fixed;
		top: 200px;
		left: 50px;
		z-index: 1;
		padding: 10px 15px 10px 5px;
		font-size: 14px;
		color: #fff;
		border-radius: 6px;
		background: linear-gradient(180deg, #083dc6 0%, #159eeb 100%);
		cursor: pointer;
		&:hover {
			opacity: 0.9;
		}
		&:active {
			opacity: 0.7;
		}
		i {
			margin-left: 5px;
			width: 24px;
			height: 24px;
			background: url("../../../assets/images/selectTop.png");
		}
	}
}
</style>
